package ThreadRunableVolite;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Ajie
 * @date 2020-12-08
 * @function threada b交叉运行
 * Java 多线程交替打印1~100
 *
 * todo 不加Sleep 全部都是  thradA 拿到锁，处理任务。 DEBUG =false;
 *
 * DEBUG =true; 全部是 threadB 拿到锁
 */
public class ThreadOrderAB_Reentrant {
    static boolean DEBUG =true;
    volatile static int i=1;
    static int MAXCOUNT = 100;

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition conditionA = lock.newCondition();
        Condition conditionB = lock.newCondition();


        Thread aThread = new Thread(new Runnable() {

            @Override
            public void run() {

                System.out.println("A run。。。");
                while (true) {
                    // 唤醒另一个线程
                    lock.lock();
                    if (i>MAXCOUNT){
                        return;
                    }
                    System.out.println("A拿到锁 work:" + (i++));
                    try {
                        if (DEBUG)
                        Thread.sleep(10 * 2);
                        if (DEBUG)
                        System.out.println("INFO: 有人唤醒了 A, A 重新获得锁 lock");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        lock.unlock(); // TODO: 2020-12-10 Exception in thread "Thread-0" java.lang.IllegalMonitorStateException 如果没有LOCK
                    }

                }

            }
        });

        Thread bThread = new Thread(new Runnable() {

            @Override
            public void run() {

                System.out.println("B run。。。");
                while (true) {
                    // 唤醒另一个线程
                    lock.lock();
                    if (i>MAXCOUNT){
                        return;
                    }
                    System.out.println("B拿到锁 work: " + (i++));
                    try {
                        if (DEBUG)
                        Thread.sleep(10 * 2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }

            }
        });


        aThread.start();
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        bThread.start();
    }


}
